package Offer.offer2016;

import domain.ComplexListNode;

public class Test26 {

    public static void main(String[] args) {
        ComplexListNode node1 = new ComplexListNode(1);
        ComplexListNode node2 = new ComplexListNode(2);
        ComplexListNode node3 = new ComplexListNode(3);
        ComplexListNode node4 = new ComplexListNode(4);
        ComplexListNode node5 = new ComplexListNode(5);
        ComplexListNode node6 = new ComplexListNode(6);
//	      node1.next=node2;
//	      node2.next=node3;
//	      node3.next=node4;
//	      node4.next=node5;
//	      node5.next=node6;
//	      node6.next=null;
        node1.next = null;
        ComplexListNode newhead = cloneList(node1);
        ComplexListNode p = newhead;
        while (p != null) {
            System.out.print(p.val);
            System.out.print(" ");
            p = p.next;
        }

    }

    public static ComplexListNode cloneList(ComplexListNode head) {
        cloneNode(head);
        setSibling(head);
        return newNode(head);

    }

    public static void cloneNode(ComplexListNode head) {
        ComplexListNode p = head;
        while (p != null) {
            ComplexListNode clone = new ComplexListNode();
            clone.val = p.val;
            clone.next = p.next;
            p.next = clone;
            p = clone.next;
        }
    }

    public static void setSibling(ComplexListNode head) {
        ComplexListNode p1 = head;
        while (p1 != null) {
            ComplexListNode p2 = p1.next;
            if (p1.sibling != null) {
                p2.sibling = p1.sibling.next;
            }
            p1 = p2.next;
        }
    }

    public static ComplexListNode newNode(ComplexListNode head) {
        ComplexListNode newHead = null;
        ComplexListNode p1 = head;
        ComplexListNode p2 = null;
        if (p1 != null) {
            newHead = p1.next;

            while (p1.next.next != null) {
                p2 = p1.next;
                p1.next = p2.next;
                p2.next = p2.next.next;
                p1 = p1.next;
                p2 = p2.next;
            }
        }
        return newHead;
    }
}
